//
//  BackgroundLayer.m
//  SCRAP_ObjC
//
//  Created by Capstone Design Fall 2010 on 10/18/10.
//  Copyright 2010 Thunderwear. All rights reserved.
//

#import "cocos2d.h"
#import "BackgroundLayer.h"
#import "Stack.h"
#import "FPoint.h"
#import "FPoint.h"
#import "ScoreLayer.h"
#import "Constants.h"
#import "StackAdditions.h"
#import "MenuScene.h"

static BOOL scoreMode;

@implementation BackgroundLayer


@synthesize playerList, menu, opacityLayer, startButton, schedPlayers, menuMode, corners, circles, movingCirclePreviousPosition, cornerScores, playerScheduling, roundLimit, scoreLimit;
@synthesize playerLabels, currentPlayerLabel;
@synthesize currentRound, disconnectElapsedTime;
@synthesize endGameTimer, endRoundButton, endRoundMenu, timerLabel;
@synthesize gamePlayable, cornerChoosing;
@synthesize emptyBacks;
@synthesize nameLabels, nameStrings;
@synthesize patDebugging;

- (void) update:(ccTime)dt
{
//	NSLog(@"%fl", dt);
	if([playerList count] > 0)
		[gameSession sendMessage:@"Ping" toPeer:nil];
	
}

+(BackgroundLayer*) initWithRoundLimit:(int) limit
{
	BackgroundLayer *blayer = [BackgroundLayer node];
	blayer.roundLimit = limit;
	blayer.scoreLimit = 0;
	NSLog(@"Initting with round limit:%i", limit);
	return blayer;
}

+(BackgroundLayer*) initWithScoreLimit:(int) limit
{
	BackgroundLayer *blayer = [BackgroundLayer node];
	blayer.scoreLimit = limit;
	blayer.roundLimit = 0;
	NSLog(@"Initting with score limit:%i", limit);
	return blayer;
}

- (id) init
{
	patDebugging = FALSE;
	gamePlayable = FALSE;
	cornerChoosing = FALSE;
	endGameTimer = 0;
	if( (self = [super init] ))
	{	
//		self.color = ccc3(25, 225, 25);
		//[self startPicker];
		scoreMode = FALSE;
		self.isTouchEnabled = TRUE;
		background = [CCSprite spriteWithFile: @"bkgr_ipad.png"];
		CCColorLayer *layer = [CCColorLayer layerWithColor:ccc4(25, 175, 25, 255)];
		[self addChild:layer z:iPadBGZ];
		emptyBacks = [[NSMutableArray alloc] init];
		
		disconnectElapsedTime = 0;
		
		size = [[CCDirector sharedDirector] winSize];
		center = ccp(size.width / 2, size.height / 2);
		
		//portals = [[NSMutableArray alloc] initWithCapacity: 4];
		
		[background setPosition:center];
		
		
		stackLayout = [[StackData alloc] initLayout];
		
		playerList = [[NSMutableArray alloc] initWithCapacity: 4];

		
		cornerPoints = [[NSMutableArray alloc] initWithCapacity: 4];
//		[cornerPoints addObject:(id)&ccp(0, size.height)];
//		[cornerPoints addObject:(id)&ccp(size.width, size.height)];
//		[cornerPoints addObject:(id)&ccp(0, 0)];
//		[cornerPoints addObject:(id)&ccp(size.width, 0)];
		[cornerPoints push:[[FPoint alloc] initWithCGPoint:ccp(0, size.height)]];
		[cornerPoints push:[[FPoint alloc] initWithCGPoint:ccp(size.width, size.height)]];
		[cornerPoints push:[[FPoint alloc] initWithCGPoint:ccp(size.width, 0)]];
		[cornerPoints push:[[FPoint alloc] initWithCGPoint:ccp(0, 0)]];
		
		//Set up colors
		colors = [[NSMutableArray alloc] initWithCapacity:4];
		[colors push:@"blue"]; //top left
		[colors push:@"red"]; //top right
		[colors push:@"purple"]; //bottom right
		[colors push:@"yellow"]; //bottom left
		
		
		cornerRadius = 100;
		

		
		[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
		
		[self addChild:background z:iPadBGZ];
		
		CCLabel *endRoundLabel = [CCLabel labelWithString:@"End Round" fontName:SCRAPFont fontSize:20];
		endRoundButton = [CCMenuItemLabel itemWithLabel:endRoundLabel target:self selector:@selector(endRoundButtonPress)];
		CCMenuItemLabel *endRoundButton2 = [CCMenuItemLabel itemWithLabel:endRoundLabel target:self selector:@selector(endRoundButtonPress)];
		endRoundButton.rotation = 180;
		
		endRoundMenu = [CCMenu menuWithItems:endRoundButton, endRoundButton2, nil];
		endRoundMenu.position = center;
		[endRoundMenu alignItemsVerticallyWithPadding:720];
		endRoundMenu.visible = FALSE;
		[self addChild:endRoundMenu z:iPadBGZ];
		
		for(int i = 0; i < [stackLayout.stacks count]; i++)
		{
			Stack *s = [stackLayout.stacks objectAtIndex:i];
			s.opacity = 0;
			[self addChild:s z:iPadBGZ];
		}
		nameLabels = [[NSMutableArray alloc] initWithCapacity:4];
		nameStrings = [[NSMutableArray alloc] initWithCapacity:4];
		for(int i = 0; i < 4; i++)
		{
			CCLabel *label = [CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36];
			[nameLabels push:label];
			[nameStrings push:@""];
		}
		[self setUpMenu:ccp(center.x, center.y + 100)];
		
		playerList = [[NSMutableArray alloc] initWithCapacity:4];
		
		
		//debug without device for players (don't forget to comment out sendColor)
//		[self patDebug];
		
		[self setUpCorners];		
		
		[self schedule: @selector(update:) interval: 5];
		
		cards = [[NSMutableArray alloc] initWithCapacity:4*52];
		
//		[self schedule: @selector(glowEffectEnd:) interval:.7f];
	}
	return self;
}

-(void) patDebug
{
	patDebugging = TRUE;
	for(int i = 0; i < 4; i++)
	{
		NSString *name = [NSString stringWithFormat:@"Player %i", (i + 1)];
		Player *player = [[Player alloc] init];
		player.name = name;
		[playerList push:player];
		[self addPlayerToMenu:player];
		schedPlayers++;
	}
}

-(void) endGameCountdown:(ccTime) dt
{
	
}

-(void) endRoundButtonPress
{
	gamePlayable = FALSE;
	NSLog(@"Button Pressed!");
	[self updateCount:[[playerList objectAtIndex:0] rcount] forPeer:[[playerList objectAtIndex:0] peerID]];
	NSLog(@"Score layer?");
}

// scale an object with duration to scale
-(void) scaleObject:(id) object withDuration:(float) duration toScale:(float) s
{
	id action = [CCScaleTo actionWithDuration:duration scale:s];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// scale an object with duration by scale
-(void) scaleObject:(id) object withDuration:(float) duration byScale:(float) s
{
	id action = [CCScaleBy actionWithDuration:duration scale:s];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// rotate an object with duration to angle
-(void) rotateObject:(id) object withDuration:(float) duration toAngle:(float) angle
{
	id action = [CCRotateTo actionWithDuration:duration angle:angle];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// rotate an object with duration by angle
-(void) rotateObject:(id) object withDuration:(float) duration byAngle:(float) angle
{
	id action = [CCRotateBy actionWithDuration:duration angle:angle];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// move an object with duration to a point
-(void) moveObject:(id) object withDuration:(float) duration withPoint:(CGPoint) point
{
	id action = [CCMoveTo actionWithDuration:duration position:point];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// tint an object with duration with rgb color
-(void) tintObject:(id) object withDuration:(float) duration red:(int)red green:(int)green blue:(int)blue
{
	id action = [CCTintTo actionWithDuration:duration red:red green:green blue:blue];
	[object runAction:action];
}

// fade an object with duration to an opacity
-(void) fadeObject:(id) object withDuration:(float) duration withOpacity:(int) opacity
{
	id action = [CCFadeTo actionWithDuration:duration opacity:opacity];
	id ease = [CCEaseIn actionWithAction:action rate:.5];
	[object runAction:ease];
}

// creates the label for each player connecting to the device
-(void) addPlayerToMenu:(Player*)p
{
	NSLog(@"?!");
	int index = [playerList indexOfObject:p];
	CCLabel *label = [nameLabels objectAtIndex:index];
	CGPoint pt = label.position;
	[opacityLayer removeChild:label cleanup:YES];
	label = [CCLabel labelWithString:p.name fontName:SCRAPFont fontSize:36];
	label.position = pt;
	[opacityLayer addChild:label];
	[nameLabels replaceObjectAtIndex:index withObject:label];
	//for(int i = 0; i < [nameLabels count]; i++)
//	{
//		NSString *str = [nameStrings objectAtIndex:i];
//		if([str isEqualToString:@""])
//		{
//			NSLog(@"?");
//			CCLabel *dispLabel = [nameLabels objectAtIndex:i];
//			[opacityLayer removeChild:dispLabel cleanup:NO];
//			dispLabel = [CCLabel labelWithString:p.name fontName:SCRAPFont fontSize:36];
//			dispLabel.position = ccp(center.x, menu.position.y - 50 * (i + 1));
//			[nameStrings replaceObjectAtIndex:i withObject:p.name];
//			[opacityLayer addChild:dispLabel];
//			break;
//		}
//		else {
//			NSLog(@"!!");
//		}
//
//	}
//	CCLabel *dispLabel = [CCLabel labelWithString:p.name fontName:SCRAPFont fontSize:36];
//	dispLabel.position = ccp(center.x, menu.position.y - 50 * ([playerList count] + 1));
//	[opacityLayer addChild:dispLabel];
}

-(void) removePlayerFromMenuByPeerID:(NSString*)peerID
{
	for(int i = 0; i < [playerList count]; i++)
	{
		Player *p = [playerList objectAtIndex:i];
		if([p.peerID isEqualToString:peerID])
		{
			//dim corner
			for(CCSprite *c in circles)
			{
				if(c.color.r == p.color.r && c.color.g == p.color.g && c.color.b == p.color.b)
				{
					c.color = ccc3(90, 90, 90);
					c.opacity = 100;
					break;
				}
			}
			
			//change score label
			CCLabel *slabel = [cornerScores objectAtIndex:i];
			CGPoint spt = slabel.position;
			float rot = slabel.rotation;
			ccColor3B clr = slabel.color;
			[self removeChild:slabel cleanup:YES];
			slabel = [CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36];
			slabel.position = spt;
			slabel.rotation = rot;
			slabel.color = clr;
			[self addChild:slabel z:iPadMGZ];
			
			CCLabel *label = [nameLabels objectAtIndex:i];
			CGPoint pt = label.position;
			[opacityLayer removeChild:label cleanup:YES];
			label = [CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36];
			label.position = pt;
			[nameLabels replaceObjectAtIndex:i withObject:label];
			[opacityLayer addChild:label];
			[playerList removeObjectAtIndex:i];
			[cornerScores removeObjectAtIndex:i];
			break;
		}
	}
	//clear labels
	//repopulate labels
	for(int i = 0; i < [playerList count]; i++)
	{
		Player *p = [playerList objectAtIndex:i];
		CCLabel *label = [nameLabels objectAtIndex:i];
		CGPoint pt = label.position;
		[opacityLayer removeChild:label cleanup:YES];
		label = [CCLabel labelWithString:p.name fontName:SCRAPFont fontSize:36];
		label.position = pt;
		[nameLabels replaceObjectAtIndex:i withObject:label];
		[nameStrings replaceObjectAtIndex:i withObject:p.name];
		if(!gamePlayable || cornerChoosing)
		{
			[opacityLayer addChild:label];
		}

	}
	
	for(int j = [playerList count]; j < [nameLabels count]; j++)
	{
		CCLabel *label = [nameLabels objectAtIndex:j];
		CGPoint pt = label.position;
		[opacityLayer removeChild:label cleanup:YES];
		label = [CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36];
		label.position = pt;
		[opacityLayer addChild:label];
		[nameLabels replaceObjectAtIndex:j withObject:label];
		[nameStrings replaceObjectAtIndex:j withObject:@""];
	}
	
	if ([playerList count] == 1 && gamePlayable)
	{
		[self endRoundButtonPress];
	}
}

// update function for listening to populate the player list
-(void) updateDisplayedPlayerList:(ccTime)dt
{
//	NSLog(@"Round limit:%i", roundLimit);
//	NSLog(@"Current round:%i", currentRound);
	playerScheduling = TRUE;
//	for(int i = 0; i < [playerList count]; i++)
//	{
//		CCLabel *label = [nameLabels objectAtIndex:i];
//		NSLog(@"Label?!");
//		NSString *str = [nameStrings objectAtIndex:i];
//		Player *player = [playerList objectAtIndex:i];
//		
//		if(![player.name isEqualToString:str])
//		{
//			CGPoint pos = label.position;
//			[opacityLayer removeChild:label cleanup:YES];
//			label = [CCLabel labelWithString:player.name fontName:SCRAPFont fontSize:36];
//			label.position = pos;
//			[opacityLayer addChild:label];
//			[nameStrings replaceObjectAtIndex:i withObject:player.name];
//			NSLog(@"Player: %@ Name pos: %f , %f", player.name, pos.x, pos.y);
//		}
//		
//		if(i == [playerList count] - 1)
//		{
//			//clean up
//			for(int j = i; j < [nameLabels count]; j++)
//			{
//				label = [nameLabels objectAtIndex:j];
//				CGPoint pt = label.position;
//				[opacityLayer removeChild:label cleanup:YES];
//				label = [CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36];
//				label.position = pt;
//				[nameStrings replaceObjectAtIndex:j withObject:@""];
//			}
//		}
//	}
	if(schedPlayers < [playerList count])
	{
		for(int i = schedPlayers; i < [playerList count]; i++)
		{
			Player *p = (Player*)[playerList objectAtIndex:i];
			[self addPlayerToMenu:p];
		}
		schedPlayers = [playerList count];
	}
	else if(schedPlayers == 4)
	{
		playerScheduling = FALSE;
		[self unschedule:@selector(updateDisplayedPlayerList:)];
	}

}

// creates FPoints with appropriate corner locations and adds to corners list
-(void) setUpCorners
{
	FPoint *corner1 = [[FPoint alloc] initWithCGPoint:ccp(0, size.height)];
	FPoint *corner2 = [[FPoint alloc] initWithCGPoint:ccp(size.width, size.height)];
	FPoint *corner3 = [[FPoint alloc] initWithCGPoint:ccp(size.width, 0)];
	FPoint *corner4 = [[FPoint alloc] initWithCGPoint:ccp(0, 0)];
	
	corners = [[NSMutableArray alloc] initWithCapacity:4];
	
	[corners push:corner1];
	[corners push:corner2];
	[corners push:corner3];
	[corners push:corner4];
}

// creates the circles for choosing corners and adds them to the circles list
// also removes everything from the opacity layer
-(void) setUpCircles
{
	circles = [[NSMutableArray alloc] initWithCapacity:4];
	CCSprite *circle1 = [CCSprite spriteWithFile:@"grey_bubble.png"];
	CCSprite *circle2 = [CCSprite spriteWithFile:@"grey_bubble.png"];
	CCSprite *circle3 = [CCSprite spriteWithFile:@"grey_bubble.png"];
	CCSprite *circle4 = [CCSprite spriteWithFile:@"grey_bubble.png"];
//	circle1.position = ccp(center.x - 150, center.y + 150);
//	circle2.position = ccp(center.x + 150, center.y + 150);
//	circle3.position = ccp(center.x + 150, center.y - 150);
//	circle4.position = ccp(center.x - 150, center.y - 150);
	circle1.scale = circle2.scale = circle3.scale = circle4.scale = 1.25;
//	b,r,p,y
	circle1.color = BLUE;
	circle2.color = RED;
	circle3.color = PURPLE;
	circle4.color = YELLOW;
	
	[circles push:circle1];
	[circles push:circle2];
	[circles push:circle3];
	[circles push:circle4];
	
	[opacityLayer removeAllChildrenWithCleanup:YES];
	
	for(int i = 0; i < [circles count]; i++)
	{
		CCSprite *c = [circles objectAtIndex:i];
		c.position = [[corners objectAtIndex:i] toCGPoint];
		c.opacity = 255;
		[self addChild:[circles objectAtIndex:i] z:iPadFGZ + 2];
	}
}

// sets up the connection menu and sets the scheduler for the connecting players to be displayed
-(void) setUpMenu:(CGPoint) p
{
	
	menuMode = TRUE;
	opacityLayer = [CCColorLayer layerWithColor:ccc4(60, 60, 60, 190)];
	[self addChild:opacityLayer z:iPadFGZ + 1];
	
//	CCLabel *startLabel = [CCLabel labelWithString:@"Start Game" fontName:SCRAPFont fontSize:48];
	CCSprite *startSprite = [CCSprite spriteWithFile:@"purple.png"];
	CCSprite *startSpriteS = [CCSprite spriteWithFile:@"purple_select.png"];
//	startButton = [CCMenuItemLabel itemWithLabel:startLabel target:self selector:@selector(startButtonAction)];
	startButton = [CCMenuItemSprite itemFromNormalSprite:startSprite selectedSprite:startSpriteS target:self selector:@selector(startButtonAction)];
	startButton.scale = 1.25;
	
	schedPlayers = [playerList count];
	
	menu = [CCMenu menuWithItems:startButton, nil];
	menu.position = p;
	[menu alignItemsVertically];
	
	for(CCLabel *l in nameLabels)
	{
		l.position = ccp(p.x, p.y - 50 - 50 * ([nameLabels indexOfObject:l] + 1));
		[opacityLayer addChild:l];
	}
	
	[self addChild:menu z:iPadFGZ + 5];
	
	//[self schedule: @selector(updateDisplayedPlayerList:) interval:.1];
}

//removes the opacity layer (retaining it in case needed for pause/scoreboard)
//also releases/cleans up menu and removes it from the layer
-(void) killMenu
{
	//[opacityLayer retain];
	//[self removeChild:opacityLayer cleanup:NO];
	//id action = [CCFadeTo actionWithDuration:1 opacity:0];
//	id ease = [CCEaseIn actionWithAction:action rate:.1];
//	[opacityLayer runAction:ease];
	[self fadeObject:opacityLayer withDuration:1 withOpacity:0];
	[self removeChild:menu cleanup:YES];
	menu = nil;
}

//removes all circle sprites from layer and memory
//also releases circles list (since it's not needed after the beginning)
-(void) killCircles
{
	for(int i = 0; i < [circles count]; i++)
	{
		CCSprite *circle = [circles objectAtIndex:i];
		[self removeChild:circle cleanup:YES];
	}
	[circles release];
	circles = nil;
}

// finds the general direction from a point to the center
-(CGPoint) directionOfCenter:(CGPoint)p
{
	CGPoint dirOfCenter = ccp(center.x - p.x, center.y - p.y);
	float len = dirOfCenter.x * dirOfCenter.x + dirOfCenter.y * dirOfCenter.y;
	len = sqrt(len);
	dirOfCenter = ccp(dirOfCenter.x / len, dirOfCenter.y / len);
	return dirOfCenter;
}

// creates the labels for each player's corner reserve counts
-(void) setUpScoreCorners
{
	cornerScores = [[NSMutableArray alloc] initWithCapacity:4];
	for(int i = 0; i < [playerList count]; i++)
	{
		Player *p = [playerList objectAtIndex:i];
		CCLabel *scoreLabel = [CCLabel labelWithString:p.rString fontName:SCRAPFont fontSize:36];
		scoreLabel.color = ccc3(0,0,0);//ccc3(80, 80, 80);
		CGPoint dirOfCenter = [self directionOfCenter:p.corner];
		
		if(dirOfCenter.x < 0)
			dirOfCenter.x = -1;
		else {
			dirOfCenter.x = 1;
		}
		
		if(dirOfCenter.y < 0)
			dirOfCenter.y = -1;
		else {
			dirOfCenter.y = 1;
		}

		float distFromCorner = 50;
		scoreLabel.position = ccp(p.corner.x + dirOfCenter.x * distFromCorner, p.corner.y + dirOfCenter.y * distFromCorner);
		if(dirOfCenter.x < 0 && dirOfCenter.y < 0)
		{
			scoreLabel.rotation = 45;
		}
		else if(dirOfCenter.x < 0 && dirOfCenter.y > 0)
		{
			scoreLabel.rotation = 135;
		}
		else if(dirOfCenter.x > 0 && dirOfCenter.y > 0)
		{
			scoreLabel.rotation = 225;
		}
		else
		{
			scoreLabel.rotation = 315;
		}

		[self addChild:scoreLabel z:iPadMGZ];
		[cornerScores push:scoreLabel];
	}
}

// button callback for the Start Game button
-(void) startButtonAction
{
	NSLog(@"Players:%i", [playerList count]);
	if([playerList count] < 2)
	{
		//do nothing
	}
	else 
	{
//		if(playerScheduling)
//		{
//			playerScheduling = FALSE;
//			[self unschedule:@selector(updatePeerList:)];
//		}
		[menu retain];
		[self removeChild:menu cleanup:NO];
		[self setUpCircles];
		[opacityLayer removeAllChildrenWithCleanup:YES];
		
		playerLabels = [[NSMutableArray alloc] initWithCapacity:4];
		for(int i = 0; i < 4; i++)
			[playerLabels push:[CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:48]];

		Player *player = [playerList objectAtIndex:0];
		currentPlayerIndex = 0;
		[self setCurrentPlayerLabels:player];
		cornerChoosing = TRUE;
		
	}
}

-(void) setCurrentPlayerLabels:(Player*) player
{
	NSString *str = [NSString stringWithFormat:@"Tap A Corner", player.name];
	currentPlayerLabel = [CCLabel labelWithString:player.name fontName:SCRAPFont fontSize:50];
	currentPlayerLabel.position = center;
	[self addChild:currentPlayerLabel z:iPadFGZ + 5];
	for(int i = 0; i < 4; i++)
	{
		float fontSize = 48;
//		if(i % 2 == 1)
//			fontSize = 38;
		CCLabel *label = [CCLabel labelWithString:str fontName:SCRAPFont fontSize:fontSize];
		float angle = 90 + i * 90;
		float x = center.x + 360 * cos(angle * M_PI / 180.0);
		float y = center.y + 250 * sin(angle * M_PI / 180.0);
		NSLog(@"label pos:%f %f", x, y);
		label.position = ccp(x, y);
		label.rotation = angle - 90;
		if(i % 2 == 0)
			label.rotation += 180;
		[playerLabels replaceObjectAtIndex:i withObject:label];
		[self addChild:label z:iPadFGZ + 5];
	}
}

-(void) unsetCurrentPlayerLabels
{
	for(CCLabel *label in playerLabels)
	{
		[self removeChild:label cleanup:NO];
	}
	[self removeChild:currentPlayerLabel cleanup:YES];
}

-(BOOL) cornerChosen:(FPoint*)point
{
	for (FPoint* corner in corners)
	{
		if([self distanceBetweenTwoPoints:[point toCGPoint] withPointB:[corner toCGPoint]] < 75)
		{
			CGPoint cp = [point toCGPoint];
			for(Player *player in playerList)
			{
				if(player.corner.x == cp.x && player.corner.y == cp.y)
					return TRUE;
			}
		}
	}
	return FALSE;
}

-(void) growEffect:(CGPoint) point
{
	for(FPoint *corner in corners)
	{
		CGPoint nearest = [self nearestCorner:point];
		float dist = [self distanceBetweenTwoPoints:point withPointB:[corner toCGPoint]];
		CCSprite *circle = [circles objectAtIndex:[corners indexOfObject:corner]];
		if(corner.x == nearest.x && corner.y == nearest.y && dist < 480)
		{
			if([circle numberOfRunningActions] != 0)
			{
				[circle stopAllActions];
				[self scaleObject:circle withDuration:.5 toScale:3];
			}
		}
		
	}
}

-(void) rotateCurrentPlayerLabel:(CGPoint)point
{
	float fdist = [self distanceBetweenTwoPoints:point withPointB:center];
	float nameAngle = 0;
	if(point.x == center.x)
	{
		//angle = 90 or -90
		if(point.y > center.y)
			nameAngle = 180;
		else
			nameAngle = 0;
	}
	else
	{
		float tempAngle = acos((point.x - center.x) / fdist);
		tempAngle *= 180.0 / M_PI;
		float mod = 1;
		if (point.y > center.y)
		{
			mod = -1;
		}
		
		//if(point.x < center.x)
//		{
//			nameAngle += mod * (tempAngle + 90);
//		}
//		else
//		{
//			nameAngle += mod * tempAngle;
//		}
		nameAngle += mod * tempAngle - 90;
	}
//	currentPlayerLabel.rotation = nameAngle;
	currentPlayerLabel.rotation = 0;
}

// touch callback for entering touch (i.e. mouse press)
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{	
	CGPoint point = [touch locationInView:[touch view]];
	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
	float x = convertedPoint.x;
	float y = convertedPoint.y;
	
//	NSLog(@"Touched (%f,%f)\n\n",x,y);
	

//	else if([self intersectCircle:convertedPoint withPointB:ccp(size.width, size.height) withRadius:100]){
	//		[self receivedCard:[Card getRandomCard]];
//	}
	//if([self intersectCircle:convertedPoint withPointB:ccp(0, size.height) withRadius:150])
//	{
//		//top left corner :)
//	}
	
	if(currentPlayerIndex > -1 && currentPlayerIndex < [playerList count] && menuMode)
	{
		EAGLView *view = [[CCDirector sharedDirector] openGLView];
		[view setMultipleTouchEnabled:FALSE];
		float cdist = 1024;
		CCSprite *circle = [circles objectAtIndex:0];
		for (CCSprite *c in circles)
		{
			float dist = [self distanceBetweenTwoPoints:c.position withPointB:convertedPoint];
			if(dist < cdist && dist < 225)
			{
				cdist = dist;
				circle = c;
			}
		}
		
		
		if(cdist < 1024)
		{
			currentCircleIndex = [circles indexOfObject:circle];
		}
		[self growEffect:convertedPoint];
		
		
		[self rotateCurrentPlayerLabel:convertedPoint];
		
		//first see if a circle is doing an action, if so then it's not "moving" but shouldn't update origin pos
//		bool isAlreadyMoving = FALSE;
//		for(int i = 0; i < [circles count]; i++)
//		{
//			CCSprite *c = (CCSprite*)[circles objectAtIndex:i];
//			//if c has an action, set isAlreadyMoving to true.
//			if([c numberOfRunningActions])
//			{
//				isAlreadyMoving = TRUE;
//			}
//		}
//		float dist = 5000;
//		currentCircleIndex = 0;
//		for(int i = 0; i < [circles count]; i++)
//		{
//			CCSprite *c = (CCSprite*)[circles objectAtIndex:i];
//			float cdist = [self distanceBetweenTwoPoints:c.position withPointB:convertedPoint];
//			if(cdist < dist && cdist < 75 && ![self circlePlaced:c])
//			{
//				dist = cdist;
//				currentCircleIndex = i;
//			}
//		}
//		if(dist < 5000)
//		{
//			CCSprite *circle = (CCSprite*)[circles objectAtIndex:currentCircleIndex];
//			if(!isAlreadyMoving)
//				movingCirclePreviousPosition = circle.position;
//			circle.position = ccp(x, y);
//			[self removeChild:circle cleanup:NO];
//			[self addChild:circle z:iPadFGZ + 1];
//			circleIsMoving = TRUE;
//		}
	}
	if(!gamePlayable)
		return TRUE;
	
	// look for touches on waiting cards
	for (Player * player in playerList) {
		if(player.card != nil && player.card.touch==nil && [player.card pointInside:ccp(x,y)]) {
			player.card.touch = touch;
			[player.card setShadow:255];
			NSLog(@"Grabbed a touch");
			break;
		}
	}
	
	return TRUE;
}

// touch callback for moving touch (i.e. mouse moved)
-(BOOL) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint point = [touch locationInView:[touch view]];
	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
	float x = convertedPoint.x;
	float y = convertedPoint.y;
	if(menuMode)
	{
//		[self growEffect:convertedPoint];
//		for(CCSprite *circle in circles)
//			if([circle numberOfRunningActions] == 0)
//				[self scaleObject:circle withDuration:.1 toScale:1.5];
		[self rotateCurrentPlayerLabel:convertedPoint];
	}
	
	for (Player * player in playerList) {
		if (player.card != nil && player.card.touch == touch) {
//			CGPoint point = [touch locationInView:[touch view]];
//			CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
			[player.card setPosition:ccp(x + touchOffset.x, y + touchOffset.y)];
			break;
		}
	}
	return TRUE;
}

// touch callback for exiting touch (i.e. mouse release)
-(BOOL) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint point = [touch locationInView:[touch view]];	
	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
	
	/*
	 * Menu Stuff
	 */
	if(menuMode) {// && circleIsMoving) {
//		for(CCSprite *circle in circles)
//			[self scaleObject:circle withDuration:.5 toScale:1.5];
		if(currentPlayerIndex > -1 && currentPlayerIndex < [playerList count])
		{
			CCSprite *circle = (CCSprite*)[circles objectAtIndex:currentCircleIndex];
			Player *player = (Player*)[playerList objectAtIndex:currentPlayerIndex];
			float cdist = 1024;
			FPoint *closestCorner = [corners objectAtIndex:0];
			for(FPoint *fp in corners)
			{
				float dist = [self distanceBetweenTwoPoints:[fp toCGPoint] withPointB:convertedPoint];
				if(dist < cdist)
				{
					cdist = dist;
					closestCorner = fp;
				}
			}
			
			if(cdist < 225 && ![self cornerChosen:closestCorner])
			{
				player.corner = [closestCorner toCGPoint];
				circle = [circles objectAtIndex:[corners indexOfObject:closestCorner]];
				player.color = circle.color;
				player.cornerSprite = circle;
			}
			else
			{
				float angle = currentPlayerLabel.rotation;
				float nearestAngle = 0;
				float leastDist = 1024.0;
				for(int i = 0; i < 4; i++)
				{
					float dangle = -225 + i * 90;
					float adist = dangle - angle;
					if(abs(adist) < leastDist)
					{
						nearestAngle = dangle;
						leastDist = abs(adist);
					}
				}
				[self rotateObject:currentPlayerLabel withDuration:.5 toAngle:nearestAngle];
				return TRUE;
			}
			if(currentPlayerIndex < [playerList count] - 1)
			{	
				Player *pplayer = [playerList objectAtIndex:currentPlayerIndex + 1];
				if(currentPlayerIndex < [playerList count] - 1)
				{
					[self unsetCurrentPlayerLabels];
					[self setCurrentPlayerLabels:pplayer];
				}
			}
			currentPlayerIndex++;
			//if debugging on macbook, don't send color (crashes)
			if(!patDebugging)
			{
				[self sendColor:player withPortal:circle];
			}
			NSLog(@"Circle: %i", currentCircleIndex);
			[self removeChild:circle cleanup:NO];
			[self addChild:circle z:iPadMGZ];
			if(currentPlayerIndex >= [playerList count])
			{
				EAGLView *view = [[CCDirector sharedDirector] openGLView];
				[view setMultipleTouchEnabled:TRUE];
				//done
				//clean up menu and circles.
				menuMode = FALSE;
				[self killMenu];
//					[self killCircles];
				for(CCSprite *ccircle in circles)
				{
					if([self cornerCheck:ccircle.position])
					{
						[self removeChild:ccircle cleanup:NO];
					}
				}
				[self unsetCurrentPlayerLabels];
				[self setUpScoreCorners];
				[gameSession sendMessage:@"StartRound" toPeer:nil];
				endRoundMenu.visible = TRUE;
				for(int i = 0; i < [stackLayout.stacks count]; i++)
				{
					Stack *s = [stackLayout.stacks objectAtIndex:i];
					[self fadeObject:s withDuration:.3 withOpacity:255];
				}
				cornerChoosing = FALSE;
				gamePlayable = TRUE;
			}
//			}
		}		
//		circleIsMoving = FALSE;
	}
	
	/*
	 * Regular gameplay
	 */
	if(!gamePlayable)
		return TRUE;
	for(Player * player in playerList) {
		if (player.card !=nil && player.card.touch==touch) {
					
			BOOL onStack = [self cardOnStack:player.card];
			// in portal
			if ([self intersectCircle:convertedPoint withPointB:player.corner withRadius:100]) {
				
//				id action = [CCMoveTo actionWithDuration:.1 position:player.corner];
//				id ease = [CCEaseInOut actionWithAction:action rate:3];
//				[player.card runAction:ease];
				[self moveObject:player.card withDuration:.1 withPoint:player.corner];
				[self returnCard:player];
			// in stack
			}else if(onStack){
//				id action = [CCMoveTo actionWithDuration:.3 position:point];
//				id ease = [CCEaseInOut actionWithAction:action rate:3];
//				[player.card runAction: ease];
				player.roundScore += 1;
				
				[self acceptCard:player];
				player.card.touch = nil;				
				[player.card removeShadow];
				player.card = nil;
			} 
			else {
				NSLog(@"Illegal move");
				CGPoint dirOfCenter = [self directionOfCenter:player.corner];
//				id action = [CCMoveTo actionWithDuration:.3 position:ccp(player.corner.x + dirOfCenter.x * 100, player.corner.y + dirOfCenter.y * 100)];			
//				id ease = [CCEaseInOut actionWithAction:action rate:3];
				[gameSession sendMessage:@"Rejected Illegal Move" toPeer:player.peerID];
//				[player.card runAction:ease];				
				[player.card removeShadow];
				CGPoint moveToPoint = ccp(player.corner.x + dirOfCenter.x * 100, player.corner.y + dirOfCenter.y * 100);
				[self moveObject:player.card withDuration:.3 withPoint:moveToPoint];
				player.card.touch = nil;
			}
			break;
		}
	}
	return TRUE;
}

// finds the closest corner to the point p
-(CGPoint) nearestCorner:(CGPoint)p
{
	float dist = 5000;
	CGPoint point = ccp(-1, -1);
	for(int i = 0; i < [corners count]; i++)
	{
		FPoint *cornerPoint = (FPoint*)[corners objectAtIndex:i];
		CGPoint cp = [cornerPoint toCGPoint];
		float cdist = [self distanceBetweenTwoPoints:cp withPointB:p];
		if(cdist < dist && [self cornerCheck:p])
		{
			dist = cdist;
			point = cp;
		}
	}
	return point;
}

// checks if a corner is already populated
-(BOOL) cornerCheck:(CGPoint) p
{
	for(int i = 0; i < [playerList count]; i++)
	{
		Player *player = (Player*)[playerList objectAtIndex:i];
		if(player.corner.x == p.x && player.corner.y == p.y)
		{
			return FALSE;
		}
	}
	return TRUE;
}

// if the card is over a valid stack, adds to that stack and returns TRUE, otherwise returns FALSE
-(BOOL) cardOnStack:(Card*)c
{
	float dist = 5000;
	int index = 0;
	CGPoint touchPoint = ccp(c.position.x + c.touchOffset.x, c.position.y - c.touchOffset.y);
	Stack *cstack = [stackLayout.stacks lastObject];
	for(int i = 0; i < [stackLayout.stacks count]; i++)
	{
		Stack *s = [stackLayout.stacks objectAtIndex:i];

		if([self distanceBetweenTwoPoints:s.position withPointB:touchPoint] < dist && [s isValid:c])
		{
			dist = [self distanceBetweenTwoPoints:s.position withPointB:touchPoint];
			cstack = [stackLayout.stacks objectAtIndex:i];
			index = i;
		}
	}
	if(dist < 5000)
	{
		if([self intersectCircle:cstack.position withPointB:touchPoint withRadius:150])
		{
			[self removeChild:c cleanup:NO];
//				[cstack removeAllChildrenWithCleanup:YES];
//				[cstack addChild:c];
			[self addChild:c z:iPadMGZ];
			if(c.rank == 13)
			{
				CCSprite *empty = [CCSprite spriteWithFile:@"empty_back.png"];
				empty.position = cstack.position;
				empty.scale = iPadScale;
				empty.rotation = 90;
				empty.opacity = 0;
				[self addChild:empty z:iPadMGZ];
				
				CCSprite *cardBack = [CCSprite spriteWithFile:@"card_pattern.png"];
				cardBack.position = cstack.position;
				cardBack.scale = iPadScale;
				cardBack.rotation = 90;
				cardBack.opacity = 0;
				Player *p = [playerList objectAtIndex:0];
				for(int i = 0; i < [playerList count]; i++)
				{
					p = [playerList objectAtIndex:i];
					if(p.card == c)
					{
						break;
					}
				}
				cardBack.color = p.color;
				[self addChild:cardBack z:iPadMGZ];
				
				[emptyBacks push:empty];
				[emptyBacks push:cardBack];
				
				[self fadeObject:empty withDuration:1 withOpacity:255];
				[self fadeObject:cardBack withDuration:1 withOpacity:255];
			}

			if([cstack addCard:c])
			{
				NSLog(@"Accepted card");
				
				if(c.rotation == 45 || c.rotation == 225) {
					[self rotateObject:c withDuration:.3 toAngle:90];
				} else {
					[self rotateObject:c withDuration:.3 toAngle:270];
				}
				[self moveObject:c withDuration:.3 withPoint:cstack.position];
				return TRUE;
			}
		}
	}
	return FALSE;
}

-(BOOL) intersectCircle:(CGPoint)a withPointB:(CGPoint)b withRadius:(float)radius
{
	float dist = [self distanceBetweenTwoPoints:a withPointB:b];
	if (dist <= radius) {
		return TRUE;
	}
	return FALSE;
}

-(float) distanceBetweenTwoPoints:(CGPoint)a withPointB:(CGPoint)b
{
	CGFloat dx = b.x - a.x;
	CGFloat dy = b.y - a.y;
	return sqrt(dx * dx + dy * dy);
}

-(void) resetLayout
{
	NSLog(@"New Round!");
	for(Card * card in cards)
	{
		NSLog(@"%@", [card description]);
		[self removeChild:card cleanup:TRUE];
	}
	[cards removeAllObjects];
	
	for(Stack *s in stackLayout.stacks)
	{
		[s.cards removeAllObjects];
	}
	
	for(CCSprite *sprite in emptyBacks)
	{
		[self removeChild:sprite cleanup:NO];
	}
	
	[emptyBacks removeAllObjects];
	
	for(Player* p in playerList)
	{
		int index = [playerList indexOfObject:p];
		p.rcount = 13;
		p.roundScore = 0;
		p.rString = @"13";
		CCLabel *label = (CCLabel*)[cornerScores objectAtIndex:index];
		CGPoint lpos = label.position;
		float lrot = label.rotation;
		[self removeChild:label cleanup:YES];
		label = [CCLabel labelWithString:p.rString fontName:SCRAPFont fontSize:36];
		label.color = ccc3(80, 80, 80);
		label.position = lpos;
		label.rotation = lrot;
		[cornerScores replaceObjectAtIndex:index withObject:label];
		[self addChild:label z:iPadMGZ];
		p.cornerSprite.opacity = 255;
	}
	endRoundMenu.visible = TRUE;
}

-(void) resetGame
{
	[self resetLayout];
	[gameSession sendMessage:@"StartRound" toPeer: nil];
	menuMode = TRUE;
	
	[self setUpMenu:ccp(center.x, center.y + 100)];
	[self startButtonAction];
	endRoundMenu.visible = TRUE;
	
}

//for networking
-(void) returnCard:(Player*)player
{
	if(player.card != nil) {
		[self removeChild:player.card cleanup:YES];
		[gameSession sendMessage:@"Return" toPeer:player.peerID];
		//[self sendCard: player.card toPeer:player.peerID];
		//[self removeChild:player.card cleanup:TRUE];
		[player.card release];
		player.card = nil;
	}
}

//for networking
-(void) acceptCard:(Player*)player{
	
	[gameSession sendMessage:@"Accepted" toPeer: player.peerID];
}

-(void) rotateReceivedCard:(Card*)c withDirOfCenter:(CGPoint)doc
{
	if((doc.x > 0 && doc.y > 0) || (doc.x < 0 && doc.y < 0))
	{
		[self rotateObject:c withDuration:0 byAngle:45];
	}
	else {
		[self rotateObject:c withDuration:0 byAngle:-45];
	}

}

//for networking
-(void) receivedCard:(Card*)c fromPeer:(NSString*)peer
{
	if(!gamePlayable)
	{
		[gameSession sendMessage:@"Return" toPeer:peer];
		return;
	}
	for (Player * player in playerList) {
		if ([peer isEqualToString: player.peerID]) {
			CGPoint dirOfCenter = [self directionOfCenter:player.corner];
			if(dirOfCenter.x > 0)
				dirOfCenter.x = 1;
			else
				dirOfCenter.x = -1;
			
			if(dirOfCenter.y > 0)
				dirOfCenter.y = 1;
			else
				dirOfCenter.y = -1;

			
			c.position = ccp(player.corner.x + dirOfCenter.x * 65, player.corner.y + dirOfCenter.y * 65);
			[self rotateReceivedCard:c withDirOfCenter:dirOfCenter];
			player.card = c;
			[cards push:c];
			NSLog(@"%i cards now",[cards count]);
			[self addChild:c z:iPadFGZ];
			return;
		}
	}
}

-(void)updateCount:(int)rcount forPeer:(NSString*)peer
{
	for (Player * player in playerList) {
		if ([peer isEqualToString: player.peerID] || peer == player.peerID) {
			//CGPoint dirOfCenter = [self directionOfCenter:player.corner];
			player.rcount = rcount;
			player.rString = [NSString stringWithFormat:@"%i", player.rcount];
			int index = [playerList indexOfObject:player];
			CCLabel *label = (CCLabel*)[cornerScores objectAtIndex:index];
			//label.color = ccc3(80, 80, 80);
			CGPoint lpos = label.position;
			float lrot = label.rotation;
			[self removeChild:label cleanup:YES];
			label = [CCLabel labelWithString:player.rString fontName:SCRAPFont fontSize:36];
			label.color = ccc3(0,0,0);
			//ccc3(80, 80, 80);
			label.position = lpos;
			label.rotation = lrot;
			[cornerScores replaceObjectAtIndex:index withObject:label];
			[self addChild:label z:iPadMGZ];
			//Update player rcount to "Err" if player disconnects
			//
			if(player.rcount == 0 || !gamePlayable)
			{
				endRoundMenu.visible = FALSE;
				for(Player *p in playerList)
				{
					if(p.card != nil)
					{
						p.card.touch = nil;
					}
					[p.cornerSprite stopAllActions];
				}
				[self unschedule:@selector(autoFadeObjectsInOut:)];
				//round is over
				NSLog(@"Round is over!");
				for (int i = 0; i<[playerList count]; i++) {
					Player *p = [playerList objectAtIndex:i];
					int pscore = [[playerList objectAtIndex:i] roundScore] - [[playerList objectAtIndex:i] rcount];
					p.score += pscore;
					p.roundScore = pscore;
					NSString *roundmsg = [NSString stringWithFormat:@"EndRound %i",pscore];
					NSLog(@"%@ score:%@", [[playerList objectAtIndex:i] name], roundmsg);
					if(!patDebugging)
						[gameSession sendMessage:roundmsg toPeer:[[playerList objectAtIndex:i] peerID]];
				}
				currentRound++;
				NSLog(@"Round:%i RoundLimit:%i", currentRound, roundLimit);
				if([self gameIsOver])
				{
					NSLog(@"Game Over!");
					scoreMode = TRUE;
					Player *winner = [self getWinner];
					ScoreLayer *scoreLayer = [ScoreLayer layerWithPlayers:playerList withWinner:winner];
					scoreLayer.tag = 749; //leet for tag
					[self addChild:scoreLayer z:iPadFGZ + 1];
					[self schedule:@selector(checkForScoreMode:) interval:.1];
				}
				else
				{
					scoreMode = TRUE;
					ScoreLayer *scoreLayer = [ScoreLayer layerWithPlayers:playerList];
					scoreLayer.tag = 749; //leet for tag
					[self addChild:scoreLayer z:iPadFGZ + 1];
					[self schedule:@selector(checkForScoreMode:) interval:.1];
				}
			}
			else if(player.rcount == 3)
			{
				id fadeOut = [CCFadeTo actionWithDuration:1 opacity:0];
				id fadeIn = [CCFadeTo actionWithDuration:1 opacity:255];
				id repeat = [CCRepeatForever actionWithAction:[CCSequence actions:fadeOut, fadeIn, nil]];
				[player.cornerSprite runAction:repeat];
			}
			return;
		}
	}
}

-(BOOL) gameIsOver
{
	//round limit "mode"
	if(scoreLimit == 0)
	{
		
		return (currentRound >= roundLimit);
	}
	//score limit "mode"
	else if(scoreLimit > 0)
	{
		for(int i = 0; i < [playerList count]; i++)
		{
			Player *p = [playerList objectAtIndex:i];
			if(p.score >= scoreLimit)
				return TRUE;
		}
	}
	return FALSE;
}

-(Player*) getWinner
{
	Player *winner = [playerList objectAtIndex:0];
	int highestScore = -9000;
	for(Player *p in playerList)
	{
		if(p.score > highestScore)
		{
			winner = p;
			highestScore = p.score;
		}
	}
	
	NSLog(@"%@ is the Winner!!!\n\n\n", winner.name);
	return winner;
}

- (void) dealloc
{
	// cleanup the session
	[gameSession invalidateSession];
	[gameSession release];
	
	[self removeAllChildrenWithCleanup:YES];
	
	[super dealloc];
	
}



////////////////NETWORKING/////////////////////
-(void) setPicker:(iPadSession*)sesh
{
	gameSession = [sesh retain];
	gameSession.gameDelegate = self;
	[gameSession startPicker];
}

-(void) session:(iPadSession*)sesh didReceiveMessage:(NSString*)aStr fromPeer:(NSString*)peer
{
	NSLog(@"Received Data from %@, %@",peer,aStr);
	NSArray *ras = [aStr componentsSeparatedByString:@" "];
	if ([[ras objectAtIndex:0] isEqualToString:@"RCount"]) 
	{
		[self updateCount:[[ras objectAtIndex:1]intValue] forPeer:peer];
		//[self updateCount:0 forPeer:peer];
	}
	else
	{
		int rank = [[ras objectAtIndex:0] intValue];
		char suit = [[ras objectAtIndex:1] characterAtIndex:0];
		Card *newCard = [Card initWithRank:rank withSuit:suit forIPad:nil];
		
		newCard.position = ccp(size.width/2, -[newCard boundingBox].size.height);
		if(menuMode || scoreMode)
		{
			[gameSession sendMessage:@"Return" toPeer:peer];
		}
		else
		{
			[self receivedCard:newCard fromPeer:peer];
		}
	}
	
}

-(void) session:(iPadSession*)sesh newPlayer:(Player*)playa
{
	if(gamePlayable || cornerChoosing)
		return;
	else
	{
		[playerList addObject:playa];
		[self addPlayerToMenu:playa];
	}
}

-(void) sendColor:(Player*)player withPortal:(CCSprite*)p
{
//	for (int i = 0; i < 4; i++) {
//		if (ccpFuzzyEqual(player.corner, [[corners objectAtIndex:i]toCGPoint],1.0) ) {
//			 [gameSession sendMessage: [NSString stringWithFormat:@"Background %@",[colors objectAtIndex:i]] toPeer:player.peerID];
//			 break;
//		}
//	}
	[gameSession sendMessage: [NSString stringWithFormat:@"Color %@", [colors objectAtIndex:[circles indexOfObject:p]]] toPeer:player.peerID];
}

-(void) endGameDelayedDisconnect:(ccTime)dt
{
	if(disconnectElapsedTime == 0)
	{
		[gameSession invalidateSession];
		gameSession = nil;
		[[CCDirector sharedDirector] replaceScene:[CCFadeTRTransition transitionWithDuration:1 scene:[MenuScene scene]]];
		[self unschedule:@selector(endGameDelayedDisconnect:)];
		
		
//		[[CCDirector sharedDirector] runWithScene:[MenuScene scene]];
	}
	disconnectElapsedTime += 1;
}

-(void) checkForScoreMode:(ccTime)dt
{
	if(!scoreMode && !menuMode)
	{
		[self resetLayout];
		ScoreLayer *slayer = (ScoreLayer*)[self getChildByTag:749];
		[self removeChild:slayer cleanup:YES];
		[self unschedule:@selector(checkForScoreMode:)];
		if([self gameIsOver])
		{
			for(Player *p in playerList)
				[gameSession sendMessage:@"EndGame" toPeer:p.peerID];
			[self schedule:@selector(endGameDelayedDisconnect:) interval:1];
		}
		else {
			gamePlayable = TRUE;
			[gameSession sendMessage:@"StartRound" toPeer:nil];
		}
		for(Player *p in playerList)
		{
			p.rcount = 13;
			p.rString = @"13";
		}
		[self unschedule:@selector(checkForScoreMode:)];
	}
}

+(void) FalseScoreMode
{
	scoreMode = FALSE;
}


@end
